package com.kehao.leetcode.middle.sort_search;

import org.junit.Test;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

public class MergeIntervalSolution {

    public int[][] merge(int[][] intervals) {
        ArrayList<int[]> resultList = new ArrayList<>();
        resultList.add(intervals[0]);
        for (int i = 1; i < intervals.length; i++) {
            resultList.add(intervals[i]);
            for (int j = 0; j < resultList.size()-1; j++) {
                int[] last = resultList.get(resultList.size() - 1);
                int[] t = resultList.get(j);
                if((last[0]<=t[0]&&last[1]>=t[0])||(t[0]<=last[0]&&t[1]>=last[0])){
                    resultList.remove(resultList.size() - 1);
                    resultList.remove(j);
                    resultList.add(new int[]{Math.min(last[0],t[0]),Math.max(last[1],t[1])});
                    j--;
                }
            }

        }
        int[][] result = new int[resultList.size()][2];
        return resultList.toArray(result);
    }

    @Test
    public void test01(){
        int[][] intervals = {{1,3},{2,6},{8,10},{15,18}};
        int[][] merge = merge(intervals);
        System.out.println(merge);
    }

    @Test
    public void test02(){
        int[][] intervals = {{1,4},{0,2},{3,5}};
        int[][] merge = merge(intervals);
        System.out.println(merge);
    }



}
